package br.edu.unirn.controle;

import java.io.FileOutputStream;
import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

import br.edu.unirn.dao.ProdutoDAO;
import br.edu.unirn.dominio.Produto;

@ManagedBean
@ViewScoped
public class ProdutoMBean extends AbstractController{

	@PostConstruct
	public void init(){
		obj = new Produto();
		dao = new ProdutoDAO();
	}
	
	public void handleFileUpload(FileUploadEvent event) throws IOException {
        /*FacesMessage message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, message);*/
		UploadedFile file = event.getFile();
		byte[] fileContent = file.getContents();
		
		String caminho = FacesContext
							.getCurrentInstance()
							.getExternalContext()
							.getRealPath("/resources/produtos/"+file.getFileName());
		
		FileOutputStream fos = new FileOutputStream(caminho);
		fos.write(fileContent);
		fos.close();
		
		((Produto) obj).setImg(file.getFileName());
		dao.update(obj);
		addInfo("Arquivos adicionado com sucesso.");
		
    }
	
}
